package com.rem.se.test4;


class Solution {
    public ListNode subtract(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(0);
        ListNode p1 = l1, p2 = l2, cur = dummy;
        int borrow = 0;
        while (p1 != null || p2 != null) {
            int v1 = (p1 == null) ? 0 : p1.val;
            int v2 = (p2 == null) ? 0 : p2.val;
            int diff = v1 - v2 - borrow;
            if (diff < 0) {
                borrow = 1;
                diff += 10;
            } else {
                borrow = 0;
            }
            cur.next = new ListNode(diff);
            cur = cur.next;
            if (p1 != null) {
                p1 = p1.next;
            }
            if (p2 != null) {
                p2 = p2.next;
            }
        }
        while (dummy.next != null && dummy.next.val == 0) {
            dummy.next = dummy.next.next;
        }
        return (dummy.next == null) ? new ListNode(0) : dummy.next;
    }

    static class ListNode {
        int val;
        ListNode next;

        public ListNode() {
        }

        public ListNode(int x) {
            val = x;
        }
    }
}